home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_02_07 / 2n07047a < prev    next >
Text File  |  1991-04-08  |  2KB  |  95 lines

  1. /*
  2.  * File:        pnumbers.c
  3.  * Creator:     Gregg Jennings
  4.  * Version:     1.0 February 1991
  5.  * Purpose:     display formatted numbers to the console
  6.  */
  7.  
  8. #include <stdio.h>
  9.  
  10. void lpn(unsigned int n, int length, int base);
  11. void pn(unsigned int n, int base);
  12. int getlen(unsigned int n, int base);
  13.  
  14. /* some MACRO examples */
  15.  
  16. #define paddr(n) lpn(n,4,16),putch(':')
  17. #define phex(n)  lpn(n,2,16)
  18.  
  19. #define newline  putch('\n'),putch('\r')
  20.  
  21. void main()
  22. {
  23. int i;
  24.  
  25.     lpn(123,16,2);  /* display 123 dec in binary
  26.                as if printf("%016b",123) would work  */
  27.     newline;
  28.     pn(123,2);      /* display 123 dec in binary */
  29.     newline;
  30.     pn(123,8);      /* octal */
  31.     newline;
  32.     pn('\173',10);  /* 173 oct in decimal */
  33.     newline;
  34.     paddr(123);     /* display an address */
  35.     newline;
  36.     phex('A');      /* display a hex value */
  37.     newline;
  38.  
  39.             /* display the first 26 octal numbers */
  40.     for (i=0;i<26;i++) {
  41.         pn(i,8);
  42.         putch(' ');
  43.     }
  44.     newline;
  45.  
  46.             /* display the first 21 base 3 numbers */
  47.     for (i=0;i<21;i++) {
  48.         pn(i,3);
  49.         putch(' ');
  50.     }
  51.     newline;
  52. }
  53.  
  54. /*
  55.  * display a number to the console in any base from
  56.  * 2 to 36, ASCII character set only
  57.  */
  58.  
  59. void pn(unsigned int n, int base)
  60. {
  61.     if (n/base)
  62.         pn(n/base,base);
  63.     putch((n%base>9) ? n%base+'A'-10 : n%base+'0');
  64. }
  65.  
  66. /*
  67.  * display a number to the console with leading zeros
  68.  * and a certain length, and any base from 2 to 36
  69.  */
  70.  
  71. void lpn(unsigned int n, int length, int base)
  72. {
  73. register int t;
  74.     for (t=length-getlen(n,base);t>0;t--)
  75.         putch('0');
  76.     pn(n,base);
  77. }
  78.  
  79. /*
  80.  * get the display length (number of digits) of a
  81.  * number, i.e. 100 dec returns 3, 64 hex (100 dec)
  82.  * returns 2
  83.  *
  84.  * used by lpn()
  85.  */
  86.  
  87. int getlen(unsigned int n, int base)
  88. {
  89. int j;
  90.  
  91.     for (j=1;n>=base;n/=base,++j)
  92.         ;
  93.     return(j);
  94. }
  95.